package com.yc.thread;

import java.util.ArrayList;
import java.util.List;

public class 生产者与消费者模式 {

    private List<Integer> store = new ArrayList<Integer>();

    // 锁定当前对象
    public synchronized void product() throws InterruptedException {
        // 多线程判断, while 替代 if
        while (store.isEmpty() == false) {
            for (int i = 0; i < 10; i++) {
                Thread.sleep(100);
                System.out.println("生产商品:" + i);
                store.add(i);
            }
            System.out.println("生产结束:" + store.size());
            // 通知其他线程
            this.notify();
            // 当前线程等待
            this.wait();
        }
    }

    // 锁定当前对象
    public synchronized void consurme() throws InterruptedException {

        while(store.isEmpty()){
            // 通知其他线程
            this.notify();
            // 当前线程等待
            this.wait();
            while (store.isEmpty() == false) {
                Thread.sleep(150);
                System.out.println("消费商品:" + store.remove(0));
            }
            System.out.println("没有库存:" + store.size());
        }
    }

    public static void main(String[] args) {

        生产者与消费者模式 pc = new 生产者与消费者模式();

        new Thread(){
            public void run(){
                try {
                    pc.consurme();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread(){
            public void run(){
                try {
                    pc.product();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();




    }


}
